package cn.kinoko.common.aspect;

import cn.kinoko.common.aspect.annotation.CachePut;
import cn.kinoko.common.utils.SpelUtil;
import com.github.benmanes.caffeine.cache.Cache;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 分布式缓存插入切面
 *
 * @author kk
 */
@Aspect
@Component
public class CachePutAspect {

    @Resource
    private Cache<String, Object> cache;

    @Around("@annotation(cachePut)")
    public Object around(ProceedingJoinPoint joinPoint, CachePut cachePut) throws Throwable {
        // 执行业务方法
        Object target = joinPoint.proceed();
        // 检查条件，加入缓存
        if (target != null && !SpelUtil.getBoolean(joinPoint, cachePut.unless(), false)) {
            // 获取redisKey
            String redisKey = SpelUtil.getRedisKey(joinPoint, cachePut.key(), cachePut.params());
            // 设置缓存
            cache.put(redisKey, target);
        }
        return target;
    }

}
